package com.rustamg.filedialogs;

import android.app.AlertDialog;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import com.apples.hexviewer2.R;

import java.io.File;


/**
 * Created at 31/01/15 12:07
 *
 * @author rustamg
 */
public class SaveFileDialog extends FileDialog implements Toolbar.OnMenuItemClickListener {

    protected EditText mFileNameText;
    private String oldFileName;

    public void setOldFileName(String oldFileName) {
        this.oldFileName = oldFileName;
    }

    @Override
    protected int getLayoutResourceId() {
        type = 2;
        return R.layout.dialog_save_file_hex;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mFileNameText = view.findViewById(R.id.et_filename);
        if (!TextUtils.isEmpty(oldFileName))
            mFileNameText.setText(oldFileName);
        mToolbar.inflateMenu(R.menu.dialog_save_hex);
        mToolbar.getMenu().findItem(R.id.menu_apply).getIcon().setColorFilter(mIconColor, PorterDuff.Mode.SRC_IN);
        mToolbar.setOnMenuItemClickListener(this);
    }

    @Override
    public void onFileSelected(final File file) {
        if (file.isFile()) {
            confirmOverwrite(file);
        } else {
            super.onFileSelected(file);
        }
    }

    private void confirmOverwrite(final File file) {
        new AlertDialog.Builder(getActivity())
                .setMessage(R.string.confirm_overwrite_file)
                .setPositiveButton(R.string.label_button_overwrite, (dialog, which) -> sendResult(file))
                .setNegativeButton(R.string.label_button_cancel, null)
                .create().show();
    }


    @Override
    public boolean onMenuItemClick(MenuItem menuItem) {
        if (menuItem.getItemId() == R.id.menu_apply && validate()) {
            String input = mFileNameText.getText().toString();
            String inputExtension = "";
            if (mExtension != null) {
                if (!input.endsWith("." + mExtension)) {
                    inputExtension = "." + mExtension;
                }
            }
            File result = new File(mCurrentDir, mFileNameText.getText() + inputExtension);
            if (result.exists()) {
                confirmOverwrite(result);
            } else {
                sendResult(result);
            }
        }
        return false;
    }

    private boolean validate() {
        String input = mFileNameText.getText().toString();
        if (TextUtils.isEmpty(input)) {
            return false;
        }
        return !input.matches("^[^A-Za-z_\\-\\s0-9\\.]+$");
    }
}
